//
//  XWXChoosePhotos.m
//  sishunwlcar
//
//  Created by Mr_hi on 2020/1/20.
//  Copyright © 2020 zwhl. All rights reserved.
//

#define iOS7Later ([UIDevice currentDevice].systemVersion.floatValue >= 7.0f)
#define iOS8Later ([UIDevice currentDevice].systemVersion.floatValue >= 8.0f)
#define iOS9Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.0f)
#define iOS9_1Later ([UIDevice currentDevice].systemVersion.floatValue >= 9.1f)


#import "XWXChoosePhotos.h"
#import <AVFoundation/AVFoundation.h>
#import "TZImagePickerController.h"
#import "UIView+TZLayout.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"

#import "ImageBrowserViewController.h"

static XWXChoosePhotos *getImage = nil;

@interface XWXChoosePhotos()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate,TZImagePickerControllerDelegate>
{
    UIViewController *_fatherViewController;
    BOOL _isSelectOriginalPhoto;
}

@property (nonatomic, strong) UIImagePickerController *imagePickerVc;
/**最大张数*/
@property (nonatomic, assign) NSInteger MaxCount;

@end

@implementation XWXChoosePhotos

- (UIImagePickerController *)imagePickerVc {
    if (_imagePickerVc == nil) {
        _imagePickerVc = [[UIImagePickerController alloc] init];
        _imagePickerVc.delegate = self;
        // set appearance / 改变相册选择页的导航栏外观
        _imagePickerVc.navigationBar.barTintColor = ThemeColor;
        _imagePickerVc.navigationBar.tintColor = ThemeColor;
        UIBarButtonItem *tzBarItem, *BarItem;
        if (iOS9Later) {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        } else {
            tzBarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[TZImagePickerController class]]];
            
            BarItem = [UIBarButtonItem appearanceWhenContainedInInstancesOfClasses:@[[UIImagePickerController class]]];
        }
        NSDictionary *titleTextAttributes = [tzBarItem titleTextAttributesForState:UIControlStateNormal];
        [BarItem setTitleTextAttributes:titleTextAttributes forState:UIControlStateNormal];
    }
    return _imagePickerVc;
}


+(XWXChoosePhotos *)SharedChoseImg{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        getImage = [[XWXChoosePhotos alloc] init];
    });
    return getImage;
}

-(instancetype)init{
    if (self = [super init]) {
        self.allPhotos = [[NSMutableArray alloc] init];
        self.selectedPhotos = [[NSMutableArray alloc]init];
        self.selectedAssets = [[NSMutableArray alloc]init];
        self.netPhotoArr = [[NSMutableArray alloc]init];
    }return self;
}

- (void)showActionSheetInFatherViewController:(UIViewController *)fatherVC andMaxCount:(NSInteger )count andInitHeight:(void(^)(CGFloat height))HeightBlock{
    
    _fatherViewController = fatherVC;
    self.MaxCount = count;
    [self AddPhotosClicked];
}

-(void)AddPhotosClicked
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    UIAlertAction *photos = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self pushImagePickerController];
    }];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self takePhoto];
    }];
    
    [alert addAction:camera];
    [alert addAction:photos];
    [alert addAction:cancel];
    
    [_fatherViewController presentViewController:alert animated:YES completion:nil];
}

- (void)takePhoto
{
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if ((authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) && iOS8Later)
    {
        // 无权限 做一个友好的提示
        UIAlertController *alert=[UIAlertController  alertControllerWithTitle:@"未获得授权使用摄像头" message:@"请在iOS'设置-隐私-相机'中打开" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *CanCel=[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:CanCel];
        [_fatherViewController presentViewController:alert animated:YES completion:nil];
    } else { // 调用相机
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
            self.imagePickerVc.sourceType = sourceType;
            if([[[UIDevice
                  currentDevice] systemVersion] floatValue]>=8.0 && [[[UIDevice
                  currentDevice] systemVersion] floatValue]<13.0) {
                _imagePickerVc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
            } else {
                _imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
            }
            [_fatherViewController presentViewController:_imagePickerVc animated:YES completion:nil];
        } else {
            NSLog(@"模拟器中无法打开照相机,请在真机中使用");
        }
    }
    
}


#pragma mark - 拍照
- (void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        TZImagePickerController *tzImagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
        tzImagePickerVc.sortAscendingByModificationDate = NO;
        [tzImagePickerVc showProgressHUD];
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        //UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        
        // save photo and get asset / 保存图片，获取到asset
        [[TZImageManager manager] savePhotoWithImage:image completion:^(PHAsset *asset, NSError *error) {
            [[TZImageManager manager] getCameraRollAlbum:NO allowPickingImage:YES needFetchAssets:YES completion:^(TZAlbumModel *model) {
                [[TZImageManager manager] getAssetsFromFetchResult:model.result allowPickingVideo:NO allowPickingImage:YES completion:^(NSArray<TZAssetModel *> *models) {
                    [tzImagePickerVc hideProgressHUD];
                    TZAssetModel *assetModel = [models firstObject];
                    if (tzImagePickerVc.sortAscendingByModificationDate) {
                        assetModel = [models lastObject];
                    }
                    
                    [self.selectedAssets addObject:assetModel.asset];
                    [self.selectedPhotos addObject:image];
                    
                    [self.allPhotos removeAllObjects];
                    [self.allPhotos addObjectsFromArray:self.netPhotoArr];
                    [self.allPhotos addObjectsFromArray:self.selectedPhotos];
                    
                    if (self.getAllImagesBlock) {
                        self.getAllImagesBlock(self.allPhotos);
                    }
                }];
            }];
        }];
    }
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark - 选择图片
- (void)pushImagePickerController
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.MaxCount > 0 ? self.MaxCount - self.netPhotoArr.count : 1 delegate:self];
    imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePickerVc.selectedAssets = _selectedAssets; // optional, 可选的
    imagePickerVc.allowTakePicture = NO; // 在内部显示拍照按钮
    imagePickerVc.navigationBar.barTintColor = ThemeColor;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowPickingImage = YES;
    imagePickerVc.allowPickingOriginalPhoto = YES;
    imagePickerVc.sortAscendingByModificationDate = NO;
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
    }];
    if([[[UIDevice
          currentDevice] systemVersion] floatValue]>=8.0 && [[[UIDevice
          currentDevice] systemVersion] floatValue]<13.0) {
        imagePickerVc.modalPresentationStyle=UIModalPresentationOverCurrentContext;
    } else {
        imagePickerVc.modalPresentationStyle = UIModalPresentationFullScreen;
    }
    [_fatherViewController presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark .TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    // 多选
    [self.allPhotos removeAllObjects];
    [self.selectedPhotos removeAllObjects];
    [self.selectedAssets removeAllObjects];
    
    [self.allPhotos addObjectsFromArray:self.netPhotoArr];
    [self.allPhotos addObjectsFromArray:photos];
    [self.selectedPhotos addObjectsFromArray:photos];
    [self.selectedAssets addObjectsFromArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    if (self.getAllImagesBlock) {
        self.getAllImagesBlock(self.allPhotos);
    }
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingVideo:(UIImage *)coverImage sourceAssets:(id)asset {
    // 单选
    [self.allPhotos removeAllObjects];
    [self.selectedPhotos removeAllObjects];
    [self.selectedAssets removeAllObjects];
    
    [self.allPhotos addObjectsFromArray:self.netPhotoArr];
    [self.allPhotos addObject:coverImage];
    [self.selectedPhotos addObject:coverImage];
    [self.selectedAssets addObject:asset];
    if (self.getAllImagesBlock) {
        self.getAllImagesBlock(self.allPhotos);
    }
}

#pragma mark - Setter
-(void)setSelectedAssets:(NSMutableArray *)selectedAssets{
    _selectedAssets = selectedAssets;
}

-(void)setSelectedPhotos:(NSMutableArray *)selectedPhotos{
    _selectedPhotos = selectedPhotos;
}

-(void)setNetPhotoArr:(NSMutableArray *)netPhotoArr{
    _netPhotoArr = netPhotoArr;
    [self.allPhotos removeAllObjects];
    [self.allPhotos addObjectsFromArray:netPhotoArr];
    if (self.getAllImagesBlock) {
        self.getAllImagesBlock(self.allPhotos);
    }
}



@end
